package com.icez.verification_code_input_view

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection
import android.view.inputmethod.InputConnectionWrapper
import android.widget.EditText

/**
 * 验证码输入框
 * @sample
 * @author Icez
 */
@SuppressLint("AppCompatCustomView")
class VerificationCodeEditText @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : EditText(context, attrs) {

    var mVerificationCodeDelListener:VerificationCodeDelListener ?= null

    init {
        setOnKeyListener { view, i, keyEvent ->
            if(i == KeyEvent.KEYCODE_DEL && keyEvent.action == KeyEvent.ACTION_DOWN){
                mVerificationCodeDelListener?.onDelSoftListener()
            }
            false
        }
    }

    override fun onCreateInputConnection(outAttrs: EditorInfo?): InputConnection {
        return BackspaceInputConnection(super.onCreateInputConnection(outAttrs), true,mVerificationCodeDelListener)
    }


    internal class BackspaceInputConnection(target: InputConnection?, mutable: Boolean,val mVerificationCodeDelListener:VerificationCodeDelListener?) :
        InputConnectionWrapper(target, mutable) {
        override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean {
            mVerificationCodeDelListener?.onDelSoftListener()
            return super.deleteSurroundingText(beforeLength, afterLength)
        }
    }

    interface VerificationCodeDelListener{
        fun onDelSoftListener()
    }
}